#include "YaoReader.h"
extern "C"
{
    #include <libavutil/pixdesc.h>
}
YaoFrame::YaoFrame()
{
    avFrame = av_frame_alloc();
}

YaoFrame::~YaoFrame()
{
    if(avFrame != nullptr){
        av_frame_free(&avFrame);
        avFrame = nullptr;
    }
}

int YaoFrame::GetY(unsigned char* y)
{
    int width = avFrame->width;
    int height = avFrame->height;
    for(int i = 0; i < height; i++){
        memcpy(y + i * width, avFrame->data[0] + i * avFrame->linesize[0], width);
    }
    return 0;
}

int YaoFrame::GetU(unsigned char* u)
{
    int width = avFrame->width;
    int height = avFrame->height;
    for(int i = 0; i < height/2; i++){
        memcpy(u + i * width/2, avFrame->data[1] + i * avFrame->linesize[1], width/2);
    }
    return 0;
}

int YaoFrame::GetV(unsigned char* v)
{
    int width = avFrame->width;
    int height = avFrame->height;
    for(int i = 0; i < height/2; i++){
        memcpy(v + i * width/2, avFrame->data[2] + i * avFrame->linesize[2], width/2);
    }
    return 0;
}

void YaoFrame::VideoPrint()
{
    printf("=====================VideoPrint start\n");
    printf("width:%d, height:%d \n", avFrame->width, avFrame->height);
    AVPixelFormat format = (AVPixelFormat)avFrame->format;

    char * str = (char*)malloc(128);
    str = av_get_pix_fmt_string(str, 128, format);
    printf("pixelFormat: %s \n", str);

    AVColorRange colorRange = avFrame->color_range;
    printf("colorRange:%d \n", colorRange);

    AVColorSpace colorspace = avFrame->colorspace;
    printf("colorspace:%d \n", colorspace);
    printf("colorspace name:%s \n", av_get_colorspace_name(colorspace));

    AVColorPrimaries colorPrimaries = avFrame->color_primaries;
    printf("colorPrimaries:%d \n", colorPrimaries);

    AVColorTransferCharacteristic colorTrc = avFrame->color_trc;
    printf("colorTrc:%d \n", colorTrc);

    free(str);

    for(int i = 0; i < AV_NUM_DATA_POINTERS; i++){
        printf("video linesize[%d]: %d   ", i, avFrame->linesize[i]);
    }
    printf("\n");

    printf("=====================VideoPrint end\n");

}

void YaoFrame::AudioPrint()
{
    printf("=====================AudioPrint start\n");
    printf("nb_samples:%d\n", avFrame->nb_samples);
    AVSampleFormat format = (AVSampleFormat)avFrame->format;
    char * str = (char *)malloc(128);
    str = av_get_sample_fmt_string(str, 128, format);
    printf("pixelFormat: %s \n", str);

    printf("channels: %d \n", avFrame->channels);
    printf("channel_layout: %lld \n", avFrame->channel_layout);
    printf("pkt_pts: %lld \n", avFrame->pkt_pts);

    for(int i = 0; i < AV_NUM_DATA_POINTERS; i++){
        printf("audio linesize[%d]: %d   ", i, avFrame->linesize[i]);
    }
    printf("\n");
    printf("=====================AudioPrint end\n");
}

